package com.example.ymm.modules1.service.impl.sys.iot;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.my.sys.iot.IotShelf;
import com.example.ymm.modules1.entity.my.sys.iot.IotTag;
import com.example.ymm.modules1.entity.my.sys.iot.ViewIotTag;
import com.example.ymm.modules1.mapper.my.sys.IotTagMapper;
import com.example.ymm.modules1.query.sys.iot.IotTagQueryCriteria;
import com.example.ymm.modules1.query.sys.iot.ViewStorePositionQueryCriteria;
import com.example.ymm.modules1.service.dd.iot.IotHttpUtil;
import com.example.ymm.modules1.service.dto.heng.iot.ViewStorePositionDto;
import com.example.ymm.modules1.service.sys.iot.IotShelfService;
import com.example.ymm.modules1.service.sys.iot.IotTagService;
import com.example.ymm.util.EmailUtil;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Service
@DSTransactional
@DS("slave2")
@Slf4j
public class IotTagServiceImpl extends BaseServiceImpl<IotTagMapper, IotTag> implements IotTagService {

    @Autowired
    IotHttpUtil iotHttpUtil;
    @Autowired
    IotShelfService iotShelfService;

    @Override
    public TableList<ViewIotTag> tableList(IotTagQueryCriteria criteria, YmPageDto ymPageDto) {
        getPage(ymPageDto);
        List<ViewIotTag> arrs = tableList(criteria);
        PageInfo<ViewIotTag> pageInfo = new PageInfo<>(arrs);
        TableList<ViewIotTag> tableList = new TableList(pageInfo);
        return tableList;
    }

    @Override
    public List<ViewIotTag> tableList(IotTagQueryCriteria criteria) {
        return baseMapper.tableList(criteria);
    }

    @Override
    public ViewIotTag getDetail(String tagMac) {
        IotTagQueryCriteria criteria = new IotTagQueryCriteria();
        criteria.setTagMac(tagMac);
        List<ViewIotTag> viewIotTags = tableList(criteria);
        if (viewIotTags != null && viewIotTags.size() > 0) {
            return viewIotTags.get(0);
        }
        return null;
    }

    public List<IotTag> queryAll(IotTagQueryCriteria criteria) {
        List<IotTag> result =baseMapper.selectList(QueryHelpPlus.getPredicate(IotTag.class, criteria));
        return result;
    }

    @Override
    public IotTag getMac(String mac) {
        IotTagQueryCriteria criteria = new IotTagQueryCriteria();
        criteria.setTagMac(mac);
        List<IotTag> list = queryAll(criteria);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void setTagLocation(IotTag iotTag) {
        saveOrUpdate(iotTag);
    }

    @Override
    public List<String> bgTagImport(List<ViewIotTag> list) {
        /**
         * houseStoreName      匹配ms的仓库名称
         * houseLocationName   匹配ms的库位名称
         */
        System.out.println("--bgTagImport:"+list);
        List<String> error=new ArrayList<>();
        if(UtilValidate.isEmpty(list)){
            throw new YmException("导入数据不能为空!");
        }
        List<IotTag> adds=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ViewIotTag jsonObject = list.get(i);
            String houseLocationName= jsonObject.getHouseLocationName();
            String houseStoreName= jsonObject.getHouseStoreName();
            String shelfName=jsonObject.getShelfName();//架子
            String tagMac = jsonObject.getTagMac();

            if(UtilValidate.isEmpty(houseLocationName)){
                error.add("第"+(i+1)+"行 库位不能为空");
            }else{

            }
            houseLocationName=houseLocationName.trim();
            jsonObject.setHouseLocationName(houseLocationName);
            if(UtilValidate.isEmpty(tagMac)){
                error.add("第"+(i+1)+"行 标签mac不能为空");
            }
            jsonObject.setTagMac(tagMac.trim());

            //提取库位id
            String[] split = houseLocationName.split("\\|");
            BigInteger houseLocationId=null;
            for(String s:split){
                if(s.contains("库位标识:")){
                   String locationId= s.replace("库位标识:","");
                   houseLocationId= BigInteger.valueOf(Long.parseLong(locationId));
                }
            }
            jsonObject.setHouseLocationId(houseLocationId);
            if(UtilValidate.isNotEmpty(shelfName)){
                shelfName="A6C0"+shelfName.trim();
                jsonObject.setShelfMac(shelfName);
                IotTag iotTag = new IotTag();
                iotTag.setSort(i+1);
                iotTag.setTagMac(shelfName);
                iotTag.setTagType("巷道灯");
                adds.add(iotTag);
            }
            IotTag iotTag = new IotTag();

            BeanUtils.copyProperties(jsonObject,iotTag);
            iotTag.setSort(i+1);
            iotTag.setTagType("小灯");
            adds.add(iotTag);
//            if(UtilValidate.isNotEmpty(houseLocationName)&&UtilValidate.isNotEmpty(houseStoreName)){
//                 houseLocationName=houseLocationName.trim();
//                 houseStoreName=houseStoreName.trim();
//                jsonObject.setHouseLocationName(houseLocationName);
//                jsonObject.setHouseStoreName(houseStoreName);
//                ViewStorePositionDto oneStorePosition = getOneStorePosition(houseLocationName, houseStoreName);
//                if(UtilValidate.isEmpty(oneStorePosition)){
//                    error.add("第"+(i+1)+"行 ：<"+houseLocationName+":"+houseStoreName+">定位不到ms库位信息!");
//                }
//                jsonObject.setHouseLocationId(oneStorePosition.getHouseLocationId());
//            }

        }
        if(UtilValidate.isNotEmpty(error)){
            return error;
        }
        saveOrUpdateBatch(adds);
//        for (int i = 0; i < list.size(); i++) {
//
//            System.out.println("---iotTag:"+iotTag);
//            saveOrUpdate(iotTag);
//
//        }
        return error;

    }

    @Override
    public List<ViewStorePositionDto> getStorePosition(ViewStorePositionQueryCriteria criteria) {
        return baseMapper.getStorePosition(criteria);
    }

    @Override
    public List<IotTag> findXiandaoDengByTagMacIn(List<String> tagMacIn) {
        IotTagQueryCriteria criteria=new IotTagQueryCriteria();
        criteria.setTagMacIn(tagMacIn);
        return baseMapper.findXiandaoDengByTagMacIn(criteria);
    }

    public ViewStorePositionDto getOneStorePosition(String houseLocationName, String houseStoreName) {
        ViewStorePositionQueryCriteria criteria=new ViewStorePositionQueryCriteria();
        criteria.setHouseLocationName(houseLocationName);
        criteria.setHouseStoreName(houseStoreName);
        List<ViewStorePositionDto> dtos=getStorePosition(criteria);
        if(dtos.size()>0){
            return dtos.get(0);
        }
        return null;
    }


    @Override
    public List<IotTag> shelfTags(IotTagQueryCriteria criteria) {
        return baseMapper.shelfTags(criteria);
    }


    @Override
    public void openTag(String tagMac) {
        List<String> tagMacs=new ArrayList<>();
        tagMacs.add(tagMac);
        Gson gson = new Gson();
        String jsonStr = gson.toJson(tagMacs);
        //库位标签灯亮起
        JSONObject jsonObject = iotHttpUtil.httpPostStr("/iot/easyfinder/bgTag/light", jsonStr);
        System.out.println("--标签灯亮起："+jsonObject);
        JSONArray jsonArray1=null;
        if(jsonObject.getInteger("code")==200){
            try{
//                jsonArray1 = jsonObject.getJSONArray("data");
//                for (int a=0;a< jsonArray1.size();a++){
//                    String i_tagMac = jsonArray1.getString(a);
//                    if(i_tagMac.equals(tagMac)){
//                        IotTag iotTag = getById(tagMac);
//                        if(UtilValidate.isNotEmpty(iotTag)){
//                            iotTag.setStatus(1);
//                            saveOrUpdate(iotTag);
//                        }
//
//                    }
//                }
                IotTagQueryCriteria criteria=new IotTagQueryCriteria();
                criteria.setTagMacIn(tagMacs);
                criteria.setStatus(1);
                batchUpStatus(criteria);
                log.info("---修改标签开启状态:"+tagMacs);


            } catch (Exception e) {
                log.error("签灯亮起请求异常2："+e.getMessage());
            }
        }else{
            log.error("签灯亮起请求异常1："+jsonObject);

        }
    }


    @Override
    public JSONObject closeTagOne(ViewIotTag iotTag) {
        String s="配件1区";
        if(UtilValidate.isNotEmpty(iotTag.getHouseLocationName())){
            s=iotTag.getHouseLocationName();
        }
        List<String> tagMacs=new ArrayList<>();
        tagMacs.add(iotTag.getTagMac());
        return closeTagBatch(tagMacs,s);
    }

    @Override
    public JSONObject closeTagBatch(List<String> tagMacs, String locationname) {

        JSONObject send=new JSONObject();
        send.put("tagMacs",tagMacs);
        // 分库区指定网关
//        if(locationname.contains("配件2区")){
//            send.put("gatewayMacList",new String[]{"30EB1F5E9D98"});
//        }else{
//            send.put("gatewayMacList",new String[]{"30EB1F5B122C"});
//        }
        send.put("gatewayMacList",new String[]{"30EB1F5B12B8"});

        return sendCloseTagFn(send);
    }

    @Override
    public JSONObject closeTag(String tagMac,  String locationname) {
        List<String> tagMacs=new ArrayList<>();
        tagMacs.add(tagMac);
        return closeTagBatch(tagMacs,locationname);
    }


    public JSONObject sendCloseTagFn(JSONObject send){

        String url="/iot/easyfinder/bgTag/lightByLightModeId";

        send.put("lightOff",true);
        send.put("lightModeId","301");


        Gson gson = new Gson();
        String jsonStr = gson.toJson(send);
        log.info("--关灯参数 /lightByLightModeId："+jsonStr);
        //库位标签 灭灯
        JSONObject jsonObject = iotHttpUtil.httpPostStr(url, jsonStr);
        JSONArray jsonArray1=null;
        if(jsonObject.getInteger("code")==200){
            try{
//                jsonArray1 = jsonObject.getJSONArray("data");
//                for (int a=0;a< jsonArray1.size();a++){
//                    String i_tagMac = jsonArray1.getString(a);
//                    IotTag iotTag = getById(i_tagMac);
//                    if(UtilValidate.isNotEmpty(iotTag)){
//                        iotTag.setStatus(0);
//                        saveOrUpdate(iotTag);
//                    }
//                }
                JSONArray jsonArray = send.getJSONArray("tagMacs");
                List<String> tagMacs=new ArrayList<>();
                for (int i = 0; i < jsonArray.size(); i++) {
                    String string = jsonArray.getString(i);
                    tagMacs.add(string);
                }
                IotTagQueryCriteria c1=new IotTagQueryCriteria();
                c1.setTagMacIn(tagMacs);
                c1.setStatus(0);
                batchUpStatus(c1);

            } catch (Exception e) {
                log.error("签灯关灯请求异常2："+e.getMessage());
            }
        }else{
            log.error("签灯关灯请求异常1："+jsonObject);
            EmailUtil.sendEmail("1055162826@qq.com","关灯失败:"+jsonStr,jsonObject.toJSONString());

        }
        return jsonObject;
    }



    @Override
    public void allCloseTag() {
        IotTagQueryCriteria criteria=new IotTagQueryCriteria();
        criteria.setStatus(1);
        List<IotTag> iotTags = queryAll(criteria);
        if(UtilValidate.isEmpty(iotTags)){
            throw new YmException("没有亮起状态的灯");
        }
        List<String> tagMacs=new ArrayList<>();

        for(IotTag iotTag:iotTags){
            tagMacs.add(iotTag.getTagMac());
        }
        Gson gson = new Gson();
        String jsonStr = gson.toJson(tagMacs);
        //库位标签 灭灯
        JSONObject jsonObject = iotHttpUtil.httpPostStr("/iot/easyfinder/bgTag/lightOff", jsonStr);
        JSONArray jsonArray1=null;
        if(jsonObject.getInteger("code")==200){
            try{
//                jsonArray1 = jsonObject.getJSONArray("data");
//                for (int a=0;a< jsonArray1.size();a++){
//                    String i_tagMac = jsonArray1.getString(a);
//                    IotTag iotTag = getById(i_tagMac);
//                    if(UtilValidate.isNotEmpty(iotTag)){
//                        iotTag.setStatus(0);
//                        saveOrUpdate(iotTag);
//                    }
//                }
                IotTagQueryCriteria c2=new IotTagQueryCriteria();
                c2.setTagMacIn(tagMacs);
                c2.setStatus(0);
                batchUpStatus(c2);
                log.info("---修改标签关闭状态"+iotTags);


            } catch (Exception e) {
                log.error("签灯关灯请求异常2："+e.getMessage());
            }
        }else{
            log.error("签灯关灯请求异常1："+jsonObject);

        }
    }


    @Override
    public void batchUpStatus(IotTagQueryCriteria criteria) {
        baseMapper.batchUpStatus(criteria);
    }
}
